package com.blockchain.securewallet.activities;

import android.os.Bundle;
import android.os.Handler;
import android.support.constraint.ConstraintLayout;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.blockchain.securewallet.R;
import com.blockchain.securewallet.WalletApp;
import com.blockchain.securewallet.base.BaseActivity;
import com.blockchain.securewallet.utils.Logger;
import com.blockchain.securewallet.utils.ShowPopUtil;
import com.blockchain.securewallet.utils.StringUtil;
import com.blockchain.securewallet.utils.ToastUtils;
import com.blockchain.securewallet.utils.UIHelper;
import com.kyleduo.switchbutton.SwitchButton;
import com.wangnan.library.GestureLockView;
import com.wangnan.library.listener.OnGestureLockListener;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class SecureSettingActivity extends BaseActivity implements OnGestureLockListener {

    @BindView(R.id.tv_title)
    TextView tvTitle;

    @BindView(R.id.tv_tips)
    TextView tv_tips;

    @BindView(R.id.gesture_lock)
    GestureLockView lockView;

    @BindView(R.id.sb_custom_switch)
    SwitchButton switchButton;

    @BindView(R.id.fl_gesture)
    FrameLayout cvLockView;

    @BindView(R.id.tv_reset)
    TextView tvReset;

    @BindView(R.id.cl_switch)
    ConstraintLayout cl_switch;

    private boolean first = true;
    private String password;

    private ShowPopUtil showPopUtil;
    private int count = 0;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_secure_setting);
        ButterKnife.bind(this);

        tvTitle.setText(R.string.set_secure);

        boolean lockSet = WalletApp.getInstance().isLockPasswordSet();
        //记录选中状态
        switchButton.setChecked(lockSet);

        if (lockSet && TextUtils.isEmpty(WalletApp.getInstance().getLockPassword())) {
            shouldShowLock(true);
        } else {
            shouldShowLock(false);
        }

        //注意这里，这是表示是否可点击的意思
        switchButton.setClickable(false);

        //设置手势监听
        lockView.setGestureLockListener(this);

        //扩大标题栏左上角箭头的点击范围
        UIHelper.expandViewTouchDelegate(tvReset, 15, 90, 60, 20);
    }


    //是否需要显示手势图布局
    private void shouldShowLock(boolean yes) {
        if (yes) {
            cvLockView.setVisibility(View.VISIBLE);
            tvReset.setVisibility(View.VISIBLE);
            tv_tips.setVisibility(View.VISIBLE);
        } else {
            cvLockView.setVisibility(View.INVISIBLE);
            tvReset.setVisibility(View.INVISIBLE);
            tv_tips.setVisibility(View.INVISIBLE);
        }
    }

    @OnClick(R.id.btn_back)
    void back() {
        finish();
    }

    @OnClick(R.id.tv_reset)
    void reset() {
        ToastUtils.showToast("重新设置");

        lockView.clearView();
        WalletApp.getInstance().saveLockPassword("");
        WalletApp.getInstance().saveLockPasswordSet(false);
        first = true;
    }

    private void initLockView(boolean isChecked) {
        first = true;
        if (isChecked) {
            shouldShowLock(true);
        } else {
//                    boolean lockSet = WalletApp.getInstance().isLockPasswordSet();
//                    String password = WalletApp.getInstance().getLockPassword();

            //设置和关闭手势密码需要输入支付密码
            //补充


            WalletApp.getInstance().saveLockPasswordSet(false);

//                    if(lockSet && !TextUtils.isEmpty(password)) {
//                        cvLockView.setVisibility(View.VISIBLE);
//                        tvReset.setVisibility(View.VISIBLE);
//                    }else {
            shouldShowLock(false);
//                    }
        }
    }


    @OnClick(R.id.cl_switch)
    void onSwitchClick() {
        //首先弹出密码输入框
        if (showPopUtil == null) {
            showPopUtil = new ShowPopUtil(R.layout.password_ensure_dialog, SecureSettingActivity.this, 0.7, 0.3) {

                @Override
                protected void initView(View view) {

                    final EditText edit_first_password = view.findViewById(R.id.edit_first_password);
                    TextView tv_cancel = view.findViewById(R.id.tv_cancel);
                    TextView tv_ok = view.findViewById(R.id.tv_ok);
                    final TextView tv_tips_pw_err = view.findViewById(R.id.tv_tips_pw_err);

                    edit_first_password.addTextChangedListener(new TextWatcher() {
                        @Override
                        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                            //Logger.ds("beforeTextChanged.");
                        }

                        @Override
                        public void onTextChanged(CharSequence s, int start, int before, int count) {
                            //如果显示了，就隐藏掉；如果隐藏了，就别管。
                            if (tv_tips_pw_err.getVisibility() == View.VISIBLE) {
                                //Logger.ds("onTextChanged 显示了，隐藏掉.");
                                tv_tips_pw_err.setVisibility(View.GONE);
                            }
                        }

                        @Override
                        public void afterTextChanged(Editable s) {
                            //Logger.ds("afterTextChanged.");
                        }
                    });

                    tv_cancel.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            showPopUtil.dismiss();
                            showPopUtil = null;
                        }
                    });

                    tv_ok.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (!edit_first_password.getText().toString().equals(WalletApp.getInstance().getPayPassword())) {

                                if (StringUtil.isEmpty(edit_first_password.getText().toString())) {
                                    tv_tips_pw_err.setText(getString(R.string.tips_password_null));
                                } else {
                                    tv_tips_pw_err.setText(getString(R.string.tips_password_error));
                                }

                                tv_tips_pw_err.setVisibility(View.VISIBLE);

                            } else {
                                if (switchButton.isChecked()) {
                                    switchButton.setChecked(false);
                                } else {
                                    switchButton.setChecked(true);
                                }
                                initLockView(switchButton.isChecked());
                                showPopUtil.dismiss();
                                showPopUtil = null;
                            }

                        }
                    });

                }
            };
        }

        showPopUtil.showPop();
    }


    @Override
    public void onStarted() {
        //不能在这里写，否则会影响到错误视图的显示
        //lockView.clearView();
    }

    @Override
    public void onProgress(String progress) {
        count++;
        //图案解锁内容改变
        Logger.ds("第" + count + "个: " + progress);

        //图案节点以数字标识，逐渐递增的结果
        //0、01、···、012467、0124678
        //最终结果为 0124678
    }

    @Override
    public void onComplete(String result) {
        //图案解锁完成
        Logger.ds("结果: " + result);

        //写在这里会影响到错误视图的显示
        //lockView.clearView();

        boolean lockSet = WalletApp.getInstance().isLockPasswordSet();

        if (first && !lockSet) {
            password = result;
            first = false;

            //请再次绘制解锁图案
            initTipsTv(true);
            tv_tips.setText(getResources().getString(R.string.tips_lock_gesture_again));

            //ToastUtils.showToast("请再次输入手势密码");
            lockView.clearView();

        } else {
            if (lockSet) {
                password = WalletApp.getInstance().getLockPassword();
            }

            if (!password.equals(result)) {
                if (lockSet) {
                    //Toast.makeText(SecureSettingActivity.this, "密码错误", Toast.LENGTH_SHORT).show();

                    initTipsTv(false);
                    tv_tips.setText(getResources().getString(R.string.tips_lock_gesture_error));
                } else {
                    //Toast.makeText(SecureSettingActivity.this, "密码输入不一致", Toast.LENGTH_SHORT).show();

                    initTipsTv(false);
                    tv_tips.setText(getResources().getString(R.string.tips_lock_gesture_error_double));
                }

                //显示错误状态millisecond毫秒后还原至初始状态
                lockView.showErrorStatus(1200);

                //显示完错误的文案后，就请再次绘制解锁图案
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //这里是主线程
                        initTipsTv(true);
                        tv_tips.setText(getResources().getString(R.string.tips_lock_gesture_again));
                    }
                }, 1200);

                first = true;
            } else {
                if (lockSet) {
                    WalletApp.getInstance().saveLockPassword("");
                    WalletApp.getInstance().saveLockPasswordSet(false);
                } else {
                    WalletApp.getInstance().saveLockPassword(password);
                    WalletApp.getInstance().saveLockPasswordSet(true);
                }
                finish();
                ToastUtils.showToast("手势密码设置成功");
            }
        }

        //重置计算次数
        count = 0;
    }

    /**
     * 根据手势输入情况显示提示文本
     *
     * @param isNormal 目前只要2种情况：正常、错误
     */
    private void initTipsTv(boolean isNormal) {
        if (isNormal) {
            tv_tips.setTextSize(12f);
            tv_tips.setTextColor(getResources().getColor(R.color.lock_tips));
        } else {
            tv_tips.setTextSize(13f);
            tv_tips.setTextColor(getResources().getColor(R.color.red_err));
        }
    }

}
